//
//  ViewController.m
//  6.11
//
//  Created by LGC on 2020/6/11.
//  Copyright © 2020年 LGC. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UIScrollViewDelegate>
@property (nonatomic,strong) UIPageControl *pageControl;
@property (nonatomic,strong) UIScrollView *scrollView;
@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];
    [self setupView];
}

- (void)setupView{
    self.scrollView = [[UIScrollView alloc]initWithFrame:self.view.bounds];
    self.scrollView.delegate = self;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.scrollView];
    
    CGFloat imgW = self.scrollView.frame.size.width;
    CGFloat imgH = self.scrollView.frame.size.height;
    for (int i = 0; i<5; i++) {
        UIImageView *imageview = [[UIImageView alloc]init];
        
        NSString * imageName = [NSString stringWithFormat:@"page%d",i];
        imageview.image = [UIImage imageNamed:imageName];
        imageview.frame = CGRectMake(imgW * i, 0, imgW, imgH);
        imageview.backgroundColor = [UIColor greenColor];
        [self.scrollView addSubview:imageview];
        
    }
    self.scrollView.contentSize = CGSizeMake(5 *imgW, imgH);
    self.scrollView.pagingEnabled = YES;
    
    
    self.pageControl = [[UIPageControl alloc ]init];
    self.pageControl.frame = CGRectMake(self.view.frame.size.width -80 -20 , 50, 80, 20);
    self.pageControl.currentPageIndicatorTintColor = [UIColor grayColor];
    self.pageControl.backgroundColor = [UIColor blueColor];
    [self.pageControl addTarget:self action:@selector(chengePage:) forControlEvents:UIControlEventTouchUpInside];
    self.pageControl.numberOfPages = 5;
    
    [self.view addSubview:self.pageControl];
    
//    scrollview.contentOffset = CGPointMake(scrollview.bounds.size.width * 3, 0);
//    self.pageControl.currentPage = 3;

}



- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat offset = scrollView.contentOffset.x;
    int pageIndex = offset / scrollView.bounds.size.width;
    
//    NSLog(@"%d",pageIndex);
    
    self.pageControl.currentPage = pageIndex;
}

-(IBAction)chengePage:(id)sender{
    NSInteger page = self.pageControl.currentPage;
//    [self.scrollView setContentOffset:CGPointMake(self.scrollView.bounds.size.width * page, 0)];
    [self.scrollView setContentOffset:CGPointMake(self.scrollView.bounds.size.width * page, 0) animated:YES];
}
@end


